package com.cqrcb.cloud.config;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.OptionHelper;
import org.apache.skywalking.apm.toolkit.log.logback.v1.x.mdc.TraceIdMDCPatternLogbackLayout;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.slf4j.MDC;

import java.util.UUID;

public class MyTraceIdMDCPatternLogbackLayout extends TraceIdMDCPatternLogbackLayout {


    static {
        defaultConverterMap.put("My", MyConverter.class.getName());
    }

    public static class MyConverter extends ClassicConverter {

        private MyConverterCommand myConverterCommand;

        @Override
        public void start() {
            super.start();
            String[] key = OptionHelper.extractDefaultReplacement(this.getFirstOption());
            if (key.length > 0 && "uuid".equals(key[0])) {
                this.myConverterCommand = new UUIDCommand();
            }
        }

        @Override
        public String convert(ILoggingEvent iLoggingEvent) {
            if (myConverterCommand != null) {
                return myConverterCommand.convert(iLoggingEvent);
            }
            return "";
        }

    }

    private interface MyConverterCommand {

        String convert(ILoggingEvent loggingEvent);
    }

    private static class UUIDCommand implements MyConverterCommand {

        @Override
        public String convert(ILoggingEvent loggingEvent) {
            return TraceContext.traceId();
//            return UUID.randomUUID().toString().replace("-", "");
        }
    }

}